<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page isELIgnored="false" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<title>Toetem - Chapter 11</title>
	<link rel="stylesheet" href="/strophe/public/css/jquery-ui-1.8.21.custom.css">
	<link rel="stylesheet" href="/strophe/public/css/toetem/client.css">
	<script type="text/javascript" src="/strophe/public/js/jquery-1.7.2.min.js"></script>
	<script type="text/javascript" src="/strophe/public/js/jquery-ui-1.8.21.custom.min.js"></script>
	<script type="text/javascript" src="/strophe/public/js/strophe.js"></script>
	<script type="text/javascript" src="/strophe/public/js/flXHR.js"></script>
	<script type="text/javascript" src="/strophe/public/js/strophe.flxhr.js"></script>
	<script type="text/javascript">
		var Toetem = {
			connection: null,
			referee: null,
			room: null,
			NS_TOETEM: "http://muchine.net/ns/toetem",
			NS_MUC: "http://jabber.org/protocol/muc",
			NS_MUC_USER: "http://jabber.org/protocol/muc#user",
			NS_MUC_OWNER: "http://jabber.org/protocol/muc#owner",
			MUC_SERVICE: "conference.openfire",
			
			onMessage: function(message) {
				var from = $(message).attr('from');
				
				if ($(message).find('waiting').length > 0) {
					// show waiting users
					$(message).find('waiting > player').each(function() {
						var button;
						if ($(this).attr('jid') == Toetem.connection.jid) {
							button = "<input type='button' class='stop-button' value='stop waiting'>";
						}
						else {
							button = "<input type='button' class='start-button' value='start game'>";
						}
						
						$('#waiting tbody').append(
							"<tr>" +
								"<td class='jid'>" + $(this).attr('jid') + "</td>" +
								"<td>" + button + "</td>" +									
							"</tr>"
						);
					});
				}
				else if ($(message).find('not-waiting').length > 0) {
					// show not-waiting users
					$(message).find('not-waiting > player').each(function() {
						var jid = $(this).attr('jid');
						$('#waiting td.jid').each(function() {
							if ($(this).text() == jid) {
								$(this).parent().remove();
								return false;
							}
						});
					});
				}
				else if ($(message).find('games').length > 0) {
					// list current games
					$(message).find('games > game').each(function() {
						var jid = Toetem.connection.jid;
						var oPlayer = $(this).attr('o-player');
						var xPlayer = $(this).attr('x-player');
						
						if (xPlayer != jid && oPlayer != jid) {
							$('#games tbody').append(
								"<tr>" +
									"<td>" + xPlayer + "</td>" +
									"<td>" + oPlayer + "</td>" +
									"<td class='jid'>" + $(this).attr('room') + "</td>" +
									"<td><input type='button' class='watch-button' value='watch game'></td>" +									
								"</tr>"
							);
						}
					});
				}
				else if ($(message).find('game-over').length > 0) {
					// remove finished game from the list
					$(message).find('game-over > game').each(function() {
						var roomJid = $(this).attr('room');
						$('#games td.jid').each(function() {
							if ($(this).text() == roomJid) {
								$(this).parent().remove();
								return false;
							}
						});
					});
				}
				// Openfire sends the referee's bare jid instead of full jid
				else if ($(message).find('x > invite').attr('from') == Strophe.getBareJidFromJid(Toetem.referee)) {
					// join the game since invitation received
					Toetem.room = from;
					
					Toetem.log("invited from " + from);
					
					$('#messages').empty();
					$('#messages').append("<div class='system'> Joined game #" + Strophe.getNodeFromJid(from) + "</div>");
					
					Toetem.log("clean messages.");
					
					Toetem.scrollChat();
					
					Toetem.log("scrolled chat.");
					
					$('#wait').removeAttr('disabled');
					$('#browser').hide();
					$('#game').show();
					
					var nick = Toetem.connection.jid;
					
					Toetem.log("show game screen. send presence: " + Toetem.room + "/" + nick);
					Toetem.connection.send($pres({to: Toetem.room + "/" + nick}).c('x', {xmlns: Toetem.NS_MUC}));
				}
				else {
					var body = $(message).children('body').text();
					if (body) {
						// show the received chat message
						var sender = Strophe.getResourceFromJid(from);
						var nickStyle = "nick";
						if (sender == Toetem.connection.jid) {
							nickStyle += " me";
						}
						
						$('#messages').append(
							"<div>&lt;<span class='" + nickStyle + "'>" + Strophe.getBareJidFromJid(sender) + "</span>&gt;" + body + "</div>"	
						);
						Toetem.scrollChat();
					}
					
					if ($(message).find('delay').length > 0) {
						// skip command processing of old messages
						return true;
					}
					
					var commandNode = $(message).find('*[xmlns="' + Toetem.NS_TOETEM + '"]');
					var command = null;
					if (commandNode.length > 0) {
						command = commandNode.get(0).tagName;
					}
					
					if (command == 'game-started') {
						$('#resign').removeAttr('disabled');
					}
					else if (command == 'game-ended') {
						$('#resign').attr('disabled', 'disabled');
						$('#leave').removeAttr('disabled');
					}
				}
				
				return true;
			},
			
			scrollChat: function() {
				var div = $('#messages').get(0);
				div.scrollTop = div.scrollHeight;
			},
			
			log: function(message) {
				$('#log').prepend("<p>" + message + "</p>");
			}
		};
		
		$(document).ready(function() {
			$('#login_dialog').dialog({
				autoOpen: true,
				draggable: false,
				modal: true,
				title: 'Connect to XMPP',
				buttons: {
					"Conect": function() {
						$(document).trigger('connect', {
							jid: $('#jid').val(),
							password: $('#password').val(),
							referee: $('#referee').val()
						});
						
// 						$('#password').val('');
						$(this).dialog('close');
					}
				}
			});
			
			$('.disconnect').click(function() {
				Toetem.connection.disconnect();
			});
			
			$('#wait').click(function() {
				Toetem.connection.sendIQ(
					$iq({to: Toetem.referee, type: "set"})
						.c("waiting", {xmlns: Toetem.NS_TOETEM})
				);
			});
			
			$('input.stop-button').live('click', function() {
				Toetem.connection.sendIQ(
					$iq({to: Toetem.referee, type: "set"})
						.c("stop-waiting", {xmlns: Toetem.NS_TOETEM})
				);
			});
			
			$('input.start-button').live('click', function() {
				Toetem.connection.sendIQ(
					$iq({to: Toetem.referee, type: "set"})
						.c('start', {xmlns: Toetem.NS_TOETEM, "with": $(this).parent().prev().text()})
				);
			});
			
			$('#input').keypress(function(ev) {
				if (ev.which == 13) {
					ev.preventDefault();
					
					var message = $(this).val();
					$(this).val('');
					
					Toetem.connection.send($msg({to: Toetem.room, type: "groupchat"}).c('body').t(message));
				}
			});
			
			$('#resign').click(function() {
				Toetem.connection.sendIQ(
					$iq({to:Toetem.referee, type: "set"})
						.c('resign', {xmlns: Toetem.NS_TOETEM})
				);
			});
			
			$('#leave').click(function() {
				Toetem.connection.send($pres({to: Toetem.room + "/" + Toetem.connection.jid, type: "unavailable"}));
				
				$('#game').hide();
				$('#browser').show();
			});
		});
		
		$(document).bind('connect', function(ev, data) {
			var conn = new Strophe.Connection("${config.boshUrl}");
			conn.connect(data.jid, data.password, function(status) {
				if (status == Strophe.Status.CONNECTED) {
					$(document).trigger('connected');
				}
				else if (status == Strophe.Status.DISCONNECTED) {
					$(document).trigger('disconnected');
				}
			});
			
			Toetem.connection = conn;
			Toetem.referee = data.referee;
		});
		
		$(document).bind('connected', function() {
			$('.disconnect').removeAttr('disabled');
			$('#wait').removeAttr('disabled');
			
			Toetem.connection.addHandler(Toetem.onMessage, null, "message");
			
			// tell the referee we're online
			Toetem.connection.send(
				$pres({to: Toetem.referee})
					.c('register', {xmlns: Toetem.NS_TOETEM})
			);
		});
		
		$(document).bind('disconnected', function() {
			Toetem.referee = null;
			Toetem.connection = null;
			
			$('.disconnect').attr('diabled', 'disabled');
			$('#wait').attr('disabled', 'disabled');
			
			$('#waiting tbody').empty();
			$('#games tbody').empty();
			
			$('#login_dialog').dialog('open');
		});
	</script>
</head>
<body>
	<h1>Toetem</h1>
	
	<div id='browser'>
		<div class='buttons'>
			<input class='disconnect button' type='button' value='disconnect'>
			<input id='wait' class='button' type='button' value='wait'>
		</div>
		
		<h2>Players Available</h2>
		<table id='waiting'>
			<thead>
				<tr>
					<th>Player</th>
					<th></th>
				</tr>
			</thead>
			<tbody>
			</tbody>
		</table>
		
		<h2>Games In Progress</h2>
		<table id='games'>
			<thead>
				<tr>
					<th>X</th>
					<th>O</th>
					<th>Room</th>
					<th></th>
				</tr>
			</thead>
			<tbody>
			</tbody>
		</table>
	</div>
	
	<div id='game' class='hidden'>
		<div class='buttons'>
			<input class='disconnect button' type='button' value='disconnect'>
			<input id='resign' class='button' type='button' value='resign' disabled='disabled'>
			<input id='leave' class='button' type='button' value='leave' disabled='disabled'>
		</div>
		
		<div id='board-area'>
			<canvas id='board' width='300' height='300'>
			</canvas>
			<div id='board-status'></div>
		</div>
		
		<div id='chat'>
			<div id='messages'>
			</div>
			<input type='text' id='input'>
		</div>
	</div>
	
	<div id='log'></div>
	
	<!-- login dialog -->
	<div id='login_dialog' class='hidden'>
		<label>JID:</label><input type='text' id='jid' value='${id}@${config.xmppDomain}'><br>
		<label>Password:</label><input type='password' id='password' value='welcome1'><br>
		<label>Toetem Referee:</label><input type='text' id='referee' value='referee@${config.xmppDomain}/referee'>
	</div>
</body>
</html>